var gridX;

Ext.onReady(function()
	{
		Ext.BLANK_IMAGE_URL = _PHP_.url.incroot + 'js/extjs/ext-2.2.1/resources/images/default/s.gif';
		Ext.form.Field.prototype.msgTarget = 'under';
		
		gridX = new Ext.grid.GridPanel
			({
				isDirty: false,
				titles: {grid: '', form: {add: '', edit: ''}},
				title: _PHP_.title.grid,
				
				el: 'extObj',
				width: 'auto',
				height: 600,
				loadMask: true,
				
				stripeRows: true,
				trackMouseOver: true,
				enableColumnMove: false,
				enableColumnResize: true,
				enableDragDrop: false,
				enableHdMenu: false,
				style: 'margin: 1em 2em;',
				
				viewConfig:
					{
						forceFit: true,
						enableRowBody: true
					},
				tbar: 
					[
						{
							xtype: 'tbbutton',
							text: 'Adicionar',
							icon: _PHP_.url.incroot+'img/admin/ext/application_add.png',
							cls: 'x-btn-text-icon',
							handler : function()
								{
									if(this.hasListener('beforeopenform'))
									{
										this.fireEvent('beforeopenform', this, 'add');
									}
									
									this.form.url = this.urls.add;
									this.formWin.setTitle(this.titles.form.add);
									this.formWin.show();
								}
						},
						{
							xtype: 'tbbutton',
							text: 'Editar',
							icon: _PHP_.url.incroot+'img/admin/ext/application_edit.png',
							cls: 'x-btn-text-icon',
							handler: function(e)
								{
									if (this.getSelectionModel().getCount() < 1) 
									{
										if (Ext.isEmpty(e.xtype)) return;
										Ext.MessageBox.alert('Atenção', 'Por favor selecione o registro que deseja editar.');
									}
									else 
									{
										if (this.getSelectionModel().getCount() > 1) 
										{
											Ext.MessageBox.alert('Atenção', 'Por favor selecione apenas um registro.');
										}
										else 
										{
											if (!this.hasListener('beforeaction')) 
											{
												this.doEdit(this.getSelectionModel().getSelected().id);
											}
											else 
											{
												this.fireEvent('beforeaction', this, 'edit');
											}
										}
									}
								}	
						},
						{
							xtype: 'tbbutton',
							text: 'Apagar',
							icon: _PHP_.url.incroot+'img/admin/ext/application_delete.png',
							cls: 'x-btn-text-icon',
							handler: function()
								{
									if(this.getSelectionModel().getCount() < 1)
									{
										Ext.MessageBox.alert('Atenção', 'Por favor selecione o registro que deseja apagar.');
									}
									else
									{
										if(this.getSelectionModel().getCount() > 1)
										{
											var ids = [];
											var selection = this.getSelectionModel().getSelections();
											for(var i=0;i<selection.length;i++)
											{
												ids.push(selection[i].id);
											}
											ids = ids.join(',');
											
											Ext.MessageBox.confirm('Atenção', 'Tem certeza de que deseja apagar os registros selecionados?', function(button)
												{
													if(button == 'yes')
													{
														var msgbox = Ext.MessageBox.wait('Processando ...', 'Aguarde');
														this.doDelete(this, ids, msgbox);
													}
												}, this);
										}
										else
										{
											var msgbox = Ext.MessageBox.wait('Processando ...', 'Aguarde');
											var ids = this.getSelectionModel().getSelected().id;
											
											this.doDelete(this, ids, msgbox);
										}
									}
								}
						}
					],
				bbar: new Ext.PagingToolbar
					({
						store: new Ext.data.Store(),
						pageSize: _PHP_.limit,
						displayInfo: true,
						paramNames:
							{limit: 'limit',
							 start: 'offset'},
						beforePageText: 'Página',
						afterPageText: 'de {0}',
						firstText: 'Primeira página',
						lastText: 'Última página',
						nextText: 'Próxima página',
						prevText: 'Página anterior',
						refreshText: 'Atualizar',
						displayMsg: 'Mostrando: {0} a {1}. Total: {2}',
						emptyMsg: 'Não ha registros no momento'
					}),
				plugins: new Ext.ux.grid.Search
					({
						width: 250,
						align: 'right',
						mode: 'local',
						position: 'top',
						showSelectAll: true,
						searchText: 'Filtro',
						selectAllText: 'Todos',
						disableModeSelection: true
					}),
				doEdit: function(id)
					{
						Ext.MessageBox.wait('Aguarde', 'Processando ...');
						var grid = this;
						grid.form.url = grid.urls.edit + id;
						Ext.Ajax.request
							({
								url: grid.form.url,
								success: function(response, options)
									{
										Ext.MessageBox.hide();
										var response = Ext.util.JSON.decode(response.responseText); 
										
										if(response.success === 'true')
										{
											if(grid.hasListener('beforeopenform'))
											{
												grid.fireEvent('beforeopenform', grid, 'edit');
											}
											
											var aftershow = function()
												{
													grid.formWin.un('show', aftershow);
													eval(response.setValues);
												};
											grid.formWin.on('show', aftershow);
											grid.formWin.setTitle(grid.titles.form.edit);
											grid.formWin.show();
										}
										else
										{
											Ext.MessageBox.alert('Erro', response.erro);
										}
									},
								failure: function(action)
									{
										Ext.MessageBox.alert('Erro', 'Não foi possivel conectar-se com o servidor, por favor tente novamente');
									}
							});
					},
				doDelete: function(grid, ids, msgbox)
					{
						var params = {ids: ids};
						
						if(grid.hasListener('beforedelete'))
						{
							grid.fireEvent('beforedelete', params);
						}
						
						Ext.Ajax.request
							({
								url: grid.urls.del,
								method: 'post',
								params: params,
								callback: function(options, success, response)
									{
										msgbox.hide();
										
										var response = Ext.util.JSON.decode(response.responseText); 
										if(response.success === 'true')
										{
											if(grid.hasListener('beforeopenform'))
											{
												grid.fireEvent('beforeopenform', grid, 'del');
											}
											grid.isDirty = true;
											grid.store.reload();
										}
										else
										{
											msgbox.alert('Erro', response.erro);
										}
									}
							});
					},
				formWin: new Ext.Window
					({
						layout: 'fit',
						
						width: '70%',
						minWidth: '70%',
						maxWidth: '70%',
						height: 420,
						minHeight: 420,
						resizable: true,
						
						closeAction: 'hide',
						modal: true,
						border: false,
						buttonAlign: 'center',
						
						buttons:
							[
								{
									text: 'Salvar',
									handler: function()
										{
											if(this.form.form.isValid())
											{
												if(!this.form.hasListener('beforesave'))
												{
													this.form.doSubmit(this);
												}
												else
												{
													this.form.fireEvent('beforesave', this.form);
												}	
											}
											else
											{
												Ext.MessageBox.alert('Erro', 'Por favor preencha os campos indicados.');
											}
										}
								},
								{
									text: 'Cancelar',
									handler: function(obj)
										{
											this.formWin.hide();
										}
								}
							],
						listeners:
							{
								'beforeshow': function(obj)
									{
										obj.parent.form.form.clearInvalid();
									},
								'hide': function(obj)
									{
										obj.parent.form.form.el.dom.scrollTop = 0
										obj.parent.form.form.reset();
										if(obj.parent.form.form.hasListener('reset'))
										{
											obj.parent.form.form.fireEvent('reset', obj.parent);
										}
									} 
							}
					}),
				form: new Ext.form.FormPanel
					({
						method: 'post',
						
						fileUpload: true,
						frame: true,
						autoScroll: true,
						
						bodyStyle: 'padding: 5px 0 5px 0',
						width: 500,
						height: 'auto',
						labelWidth: 75,
						
						defaults:
							{
								blankText: 'Este campo é obrigatório',
							 	maxLengthText: 'Limite do campo: {0} caracteres',
								maxLength: 255
							},
						monitorResize: false,
						doSubmit: function(grid)
							{
								grid.form.form.submit
									({
										url: grid.form.url||null,
										waitTitle: 'Processando ...',
										waitMsg: 'Aguarde',
										success: function(form, action)
											{
												var response = Ext.util.JSON.decode(action.response.responseText); 
												//alert(action.response.responseText); return false;
												
												if(response.success === 'true')
												{
													grid.isDirty = true;
													
													if(!grid.form.hasListener('success'))
													{
														grid.form.defaultEvents.success.apply(grid);
													}
													else
													{
														grid.form.fireEvent('success', grid.form, response);
													}
												}
												else
												{
													if(!grid.form.hasListener('erro'))
													{
														Ext.MessageBox.alert('Erro', response.erro);
													}
													else
													{
														grid.form.fireEvent('erro', grid.form, response);
													}
												}
											},
										failure: function(form, action)
											{
												if(!grid.form.hasListener('failure'))
												{
													grid.form.defaultEvents.failure();
												}
												else
												{
													grid.form.fireEvent('failure', grid.form, 'failed');
												}
											}
									});
							},
						defaultEvents:
							{
								success: function()
									{
										this.formWin.hide();
										this.store.reload();
									},
								failure: function()
									{
										Ext.MessageBox.alert('Erro', 'Não foi possivel conectar-se com o servidor, por favor tente novamente');
									}
							} 
						
					}),
				listeners:
					{
						'render': function(grid)
							{
								grid.setTitle(grid.titles.grid);
								var buttons = grid.getTopToolbar().items;
								Ext.getCmp(buttons.get(0).id).scope = grid;
								Ext.getCmp(buttons.get(1).id).scope = grid;
								Ext.getCmp(buttons.get(2).id).scope = grid;
								
								Ext.each(grid.formWin.buttons, function()
									{
										this.scope = grid;
									});
								grid.formWin.parent = grid.form.parent = grid;
								grid.formWin.add(grid.form);
							},
						'rowdblclick': function(grid, rowIndex, e)
							{
								Ext.getCmp(grid.getTopToolbar().items.get(1).id).handler.apply(grid, [e]);
							}
					}
			});
		if(row.init) row.init();
		if(window.columns) columns.init();
		if(_PHP_.onload) _PHP_.onload();
	});